package com.taiyuan.tongcheng.ui;

import java.util.ArrayList;
import java.util.List;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.taiyuan.tongcheng.adapter.SearchInfoAdapter;
import com.taiyuan.tongcheng.application.AppConfig;
import com.taiyuan.tongcheng.application.AppContext;
import com.taiyuan.tongcheng.bean.ServerStation;
import com.taiyuan.tongcheng.util.L;
import com.taiyuan.tongcheng.util.SharePreferenceUtil;
import com.tytc56.user.R;

/**
 * 
 * @Description 地图选点功能
 * @author wzq
 * @date 2015-8-10 下午2:14:26
 * @update (date)
 * @version V1.0
 */
public class AddressSelectActivity extends KJActivity implements
		OnGetPoiSearchResultListener, OnGetSuggestionResultListener,
		BDLocationListener, OnGetGeoCoderResultListener,
		OnMapStatusChangeListener ,OnItemClickListener{
	// widget
	@BindView(id = R.id.et_point_search) 
	private EditText keyWorldsViewEv;  //关键词
	@BindView(id = R.id.btn_search_btn, click = true)
	private Button btn;
	@BindView(id=R.id.btn_station_upload,click=true)
	private Button subBtn;
	@BindView(id = R.id.lv_pointinfo)
	private ListView pointList;
	@BindView(id = R.id.tv_mapselect_info)
	private TextView mapselectTv;
	@BindView(id = R.id.mapview_add)
	private MapView mapview;
	@BindView(id=R.id.btn_top_back,click=true)
	private Button backBtn;
	// 地图相关
	private PoiSearch mPoiSearch = null;
	private SuggestionSearch mSuggestionSearch = null;
	// 自定义消息相关
	private SearchInfoAdapter mapPoiAdapter;
	private List<PoiInfo> mapPoiList = new ArrayList<PoiInfo>();
	private int load_Index = 0;
	// 定位相关
	private BaiduMap mapControl = null;
	private LocationClient mLocClient;
	private BitmapDescriptor mCurrentMarker;
	private MarkerOptions markerOptions;
	private GeoCoder geoCoder;
	private boolean isFirstLoc = true;
    //overlay
	BitmapDescriptor bitMapDes = BitmapDescriptorFactory
			.fromResource(R.drawable.map_pin);
	private   SharePreferenceUtil spUtil;
	//数据
	private ServerStation staInfo = new ServerStation();
	private String inputHintString;//隐藏输入选项
	//tag
	public static final String TAG_MAP_POINT="MAP_POI";
	public static final String TAG_MAP_INPUT="KEY_EDIT_HINT";

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_map_select);
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.btn_search_btn:
			mPoiSearch.searchInCity((new PoiCitySearchOption()).city(spUtil.getLocationCity())
					.keyword(keyWorldsViewEv.getText().toString()).pageNum(0)
					.pageCapacity(5));
			break;
        
		case  R.id.btn_station_upload:
			
			if(AppConfig.debug){
				Bundle bundle =new Bundle();
				bundle.putSerializable(TAG_MAP_POINT, staInfo);
				Intent getintent=getIntent();
				getintent.putExtras(bundle);
				setResult(RESULT_OK,getintent);
				AddressSelectActivity.this.finish();
			}else{
				KJLoger.debug(staInfo.getCity()+spUtil.getLocationCity());
				//================20151101暂时去掉异地判断========================
				Bundle bundle =new Bundle();
				bundle.putSerializable(TAG_MAP_POINT, staInfo);
				Intent getintent=getIntent();
				getintent.putExtras(bundle);
				setResult(RESULT_OK,getintent);
				AddressSelectActivity.this.finish();
//				if(staInfo.getCity().equals(spUtil.getLocationCity())){
//					Bundle bundle =new Bundle();
//					bundle.putSerializable(TAG_MAP_POINT, staInfo);
//					Intent getintent=getIntent();
//					getintent.putExtras(bundle);
//					setResult(RESULT_OK,getintent);
//					AddressSelectActivity.this.finish();
//				}else{
//					showErroCustomToast("暂未开通异城配送服务,尽情期待!");
//				}
			}
			
			break;
		case R.id.btn_top_back:
			AddressSelectActivity.this.finish();
			break;
		default:
			break;
		}
	}

	@Override
	public void initWidget() {
		super.initWidget();
		spUtil=new SharePreferenceUtil(getApplicationContext(), AppConfig.SHARE_NAME);
		pointList.setOnItemClickListener(this);
		inputHintString=getIntent().getStringExtra(TAG_MAP_INPUT);
		initMap();
		initHint(inputHintString);
		keyWorldsViewEv.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(keyWorldsViewEv.getText()!=null){
				pointList.setVisibility(View.VISIBLE);
				mPoiSearch.searchInCity((new PoiCitySearchOption()).city(spUtil.getLocationCity())
						.keyword(keyWorldsViewEv.getText().toString())
						.pageNum(0).pageCapacity(5));
		    	}else{
		    		pointList.setVisibility(View.GONE);
		    		mapPoiList.clear();
		    		mapPoiAdapter.notifyDataSetChanged();
		    	}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(StringUtils.isEmpty(keyWorldsViewEv.getText())){
					pointList.setVisibility(View.GONE);
				}
			}
		});
		
	}
	
	
	/**
	 * 
	* @Description:初始化
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-28 上午10:29:20
	* @update (date)
	 */
    private void initHint(String hintString) {
    	keyWorldsViewEv.setHint(hintString);
	}

	/**
     * 
    * @Description: 初始化地图
    * @return void
    * @throws
    * @autour wzq
    * @date 2015-9-28 上午10:28:20
    * @update (date)
     */
	private void initMap() {
		mapControl = mapview.getMap();
		// 隐藏比例尺
		mapview.showScaleControl(false);
		mapview.showZoomControls(false);
		mPoiSearch = PoiSearch.newInstance();
		mPoiSearch.setOnGetPoiSearchResultListener(this);
		mSuggestionSearch = SuggestionSearch.newInstance();
		mSuggestionSearch.setOnGetSuggestionResultListener(this);
		// 初始化搜索模块，注册事件监听
		geoCoder = GeoCoder.newInstance();
		geoCoder.setOnGetGeoCodeResultListener(this);
		mapControl.setOnMapStatusChangeListener(this);// 增加监听
		MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(16);
		mapControl.animateMapStatus(u);
		// ===定位

		mapControl.setMyLocationEnabled(true); // 开启定位图层
		mLocClient = new LocationClient(getApplicationContext());// 定位初始化
		mLocClient.registerLocationListener(this);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setAddrType("all");	
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();
		L.v("证书",
				SystemTool.getSign(getApplicationContext(), "com.tytc56.user"));
	}

	@Override
	public void initData() {
		super.initData();
		mapPoiAdapter = new SearchInfoAdapter(this, mapPoiList);
		pointList.setAdapter(mapPoiAdapter);
		// sugAdapter = new ArrayAdapter<String>(this,
		// android.R.layout.simple_dropdown_item_1line);
		// pointList.setAdapter(sugAdapter);
	}

	@Override
	public void onGetSuggestionResult(SuggestionResult res) {
		if (res == null || res.getAllSuggestions() == null) {
			return;
		}
		for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
			if (info.key != null)
				ViewInject.toast(info.key);
		}
	}

	@Override
	public void onGetPoiDetailResult(PoiDetailResult result) {

		if (result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, result.getName() + ": " + result.getAddress(),
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	public void onGetPoiResult(PoiResult result) {
		if (result == null
				|| result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
			Toast.makeText(this, "未找到结果", Toast.LENGTH_LONG).show();
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			mapPoiList.clear();
			mapPoiList.addAll(result.getAllPoi());
			mapPoiAdapter.notifyDataSetChanged();
			pointList.setAdapter(mapPoiAdapter);
			// mBaiduMap.clear();
			// PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
			// mBaiduMap.setOnMarkerClickListener(overlay);
			// overlay.setData(result);
			// overlay.addToMap();
			// overlay.zoomToSpan();
			return;

		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

			// 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
			String strInfo = "在";
			for (CityInfo cityInfo : result.getSuggestCityList()) {
				strInfo += cityInfo.city;
				strInfo += ",";
			}
			strInfo += "找到结果";
			Toast.makeText(this, strInfo, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onReceiveLocation(BDLocation location) {// 定位

		// map view 销毁后不在处理新接收的位置
		if (location == null || mapview == null)
			return;
		MyLocationData locData = new MyLocationData.Builder()
				.accuracy(location.getRadius())
				// 此处设置开发者获取到的方向信息，顺时针0-360
				.direction(100).latitude(location.getLatitude())
				.longitude(location.getLongitude()).build();
		mapControl.setMyLocationData(locData);
		if (isFirstLoc) {
			isFirstLoc = false;
			LatLng ll = new LatLng(location.getLatitude(),
					location.getLongitude());
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			mapControl.animateMapStatus(u);
			geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
		}

	}

	@Override
	public void onGetGeoCodeResult(GeoCodeResult arg0) {

	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			ViewInject.toast("未能找到结果");
			return;
		}
		mapselectTv.setText(result.getAddress());
		staInfo.setLatitude(result.getLocation().latitude);
		staInfo.setLongitude(result.getLocation().longitude);
		staInfo.setPlace(result.getAddress());
		staInfo.setProvince(result.getAddressDetail().province);
		staInfo.setCity(result.getAddressDetail().city);
		KJLoger.debug(result.getAddressDetail().province+"=="+result.getAddressDetail().city);
	}

	@Override
	public void onMapStatusChange(MapStatus arg0) {

	}

	@Override
	public void onMapStatusChangeFinish(MapStatus arg0) {
		// animation(mLocaImg);
	}

	@Override
	public void onMapStatusChangeStart(MapStatus arg0) {
		LatLng currentLat = mapControl.getProjection().fromScreenLocation(
				new Point(AppContext.screenW / 2, AppContext.screenH / 2));
		geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(currentLat));

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		mapControl.clear();
//		OverlayOptions oo= new MarkerOptions().position(mapPoiList.get(arg2).location).icon(bitMapDes)
//				.zIndex(5);
//		mapControl.addOverlay(oo);
		//隐藏list
//		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(mapPoiList.get(arg2).location);
//		mapControl.animateMapStatus(u);
		MapStatus mMapStatus = new MapStatus.Builder() 
		.target(mapPoiList.get(arg2).location) 
		.zoom(17) 
		.build(); 
		//定义MapStatusUpdate对象，以便描述地图状态将要发生的变化 

		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus); 
		//改变地图状态 
		mapControl.setMapStatus(mMapStatusUpdate);
		mapselectTv.setText(mapPoiList.get(arg2).name);
		staInfo.setLatitude(mapPoiList.get(arg2).location.latitude);
		staInfo.setLongitude(mapPoiList.get(arg2).location.longitude);
		staInfo.setPlace(mapPoiList.get(arg2).name);
		staInfo.setCity(mapPoiList.get(arg2).city);
		staInfo.setProvince(spUtil.getLocationProvice());
		pointList.setVisibility(View.GONE);
		mapPoiList.clear();
		//清空输入文本
		keyWorldsViewEv.setText("");
		//关闭输入法
		SystemTool.hideKeyBoard(this);
	}
	
	
	/** 显示自定义Toast提示(来自String) **/
	public void showErroCustomToast(String text) {
		View toastRoot = LayoutInflater.from(AddressSelectActivity.this).inflate(
				R.layout.layout_common_error_toast, null);
		((TextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(AddressSelectActivity.this);
		toast.setGravity(Gravity.BOTTOM, 0, 100);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}

}
